<template>
	<div class="orderSumByCategoryEchar">
		<!-- 选择开始结束日期 -->
		<el-form label-width="80px">
			<el-form-item label="起止日期">
				<el-date-picker
					v-model="dateRange"
					type="daterange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"					
					@change="onChangeDatePicker"
				></el-date-picker>
			</el-form-item>
		</el-form>
		<!-- 图表显示区域 -->
		<div id="orderSumByCategory" style="height: 400px;"></div>
	</div>
</template>

<script setup>
import * as echarts from 'echarts';
import * as HomeAPI from '@/api/home.js';
import dayjs from 'dayjs';

import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const dateRange = ref(''); //绑定的起始日期

const query = reactive({
	dtBgn: '',
	dtEnd: ''
}); // 查询参数

// 生命周期方法
onMounted(()=>{
	init();
})

const init = () => {
	// 初始设置默认起始日期
	let dayEnd = new Date();
	let dayBgn = new Date();
	dayBgn.setDate(dayEnd.getDate() - 120);

	query.dtBgn = dayjs(dayBgn).format('YYYYMMDD');
	query.dtEnd = dayjs(dayEnd).format('YYYYMMDD');
	dateRange.value = [query.dtBgn, query.dtEnd];
	dispEchar();
};

//日期选择更改事件
const onChangeDatePicker = () => {
	if(!dateRange.value) return ;
	query.dtBgn = dayjs(dateRange.value[0]).format('YYYYMMDD');
	query.dtEnd = dayjs(dateRange.value[1]).format('YYYYMMDD');
	dispEchar();
};

//显示图表
const dispEchar = async () => {
	let result = await HomeAPI.queryOrderSumByCategory(query);
	console.log(result);
	const xAxisData = result.data.map(item => item.categoryName);
	const series1Data = result.data.map(item => item.count);
	const series2Data = result.data.map(item => item.amount);
	intiEchar(xAxisData, series1Data, series2Data);
};

//初始图表：统计商品分类销售
const intiEchar = (xAxisData, series1Data, series2Data) => {
	if (xAxisData.length == 0) {
		console.log('图表的数据还没有准备好!');
		return 0;
	}
	// 基于准备好的dom，初始化echarts实例
	let myChart = echarts.init(document.getElementById('orderSumByCategory'));
	// 绘制图表
	myChart.setOption({
		//语言：中文
		locale: 'ZH',
		//标题
		title: {
			text: '商品分类销售统计',
			left: '20%'
		},
		//提示
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		//网格
		grid: {
			left: '3%',
			right: '3%',
			bottom: '3%',
			containLabel: true
		},
		//图例
		legend: {
			orient: 'horizontal', // Try 'vertical'
			right: 'center',
			top: 30
		},
		//X轴
		xAxis: {
			data: xAxisData
		},
		//Y轴
		yAxis: [
			{
				type: 'value',
				name: '数量',
				position: 'right'
			},
			{
				type: 'value',
				name: '金额',
				position: 'left',
				alignTicks: true,
				axisLabel: {
					formatter: '￥{value}'
				}
			}
		],
		//系列
		series: [
			{
				name: '数量',
				type: 'bar',
				yAxisIndex: 0,
				data: series1Data
			},
			{
				name: '金额',
				type: 'bar',
				yAxisIndex: 1,
				data: series2Data
			}
		]
	});

	window.addEventListener('resize', () => {
		myChart.resize();
	});
};
</script>

<style scoped></style>
